<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/9
 * Time: 14:12
 */

/**
 * 创建多级目录
 * @param $path string 要创建的目录
 * @param $mode int 创建目录的模式，在windows下可忽略
 * @return string
 */
function create_dir($path, $mode = 0777)
{
    if (is_dir($path)) {
        # 如果目录已经存在，则不创建
        return "该目录已经存在";
    } else {
        # 不存在，创建
        if (mkdir($path, $mode, true)) {
            return "创建目录成功";
        } else {
            return "创建目录失败";
        }
    }
}

/**
 * 获取首字母
 * @param  string $str 汉字字符串
 * @return string 首字母
 */
function getInitials($str)
{
    if (empty($str)) {
        return '';
    }
    $fchar = ord($str{0});
    if ($fchar >= ord('A') && $fchar <= ord('z')) {
        return strtoupper($str{0});
    }

    $s1 = iconv('UTF-8', 'gb2312', $str);
    $s2 = iconv('gb2312', 'UTF-8', $s1);
    $s = $s2 == $str ? $s1 : $str;
    $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
    if ($asc >= -20319 && $asc <= -20284) {
        return 'A';
    }

    if ($asc >= -20283 && $asc <= -19776) {
        return 'B';
    }

    if ($asc >= -19775 && $asc <= -19219) {
        return 'C';
    }

    if ($asc >= -19218 && $asc <= -18711) {
        return 'D';
    }

    if ($asc >= -18710 && $asc <= -18527) {
        return 'E';
    }

    if ($asc >= -18526 && $asc <= -18240) {
        return 'F';
    }

    if ($asc >= -18239 && $asc <= -17923) {
        return 'G';
    }

    if ($asc >= -17922 && $asc <= -17418) {
        return 'H';
    }

    if ($asc >= -17417 && $asc <= -16475) {
        return 'J';
    }

    if ($asc >= -16474 && $asc <= -16213) {
        return 'K';
    }

    if ($asc >= -16212 && $asc <= -15641) {
        return 'L';
    }

    if ($asc >= -15640 && $asc <= -15166) {
        return 'M';
    }

    if ($asc >= -15165 && $asc <= -14923) {
        return 'N';
    }

    if ($asc >= -14922 && $asc <= -14915) {
        return 'O';
    }

    if ($asc >= -14914 && $asc <= -14631) {
        return 'P';
    }

    if ($asc >= -14630 && $asc <= -14150) {
        return 'Q';
    }

    if ($asc >= -14149 && $asc <= -14091) {
        return 'R';
    }

    if ($asc >= -14090 && $asc <= -13319) {
        return 'S';
    }

    if ($asc >= -13318 && $asc <= -12839) {
        return 'T';
    }

    if ($asc >= -12838 && $asc <= -12557) {
        return 'W';
    }

    if ($asc >= -12556 && $asc <= -11848) {
        return 'X';
    }

    if ($asc >= -11847 && $asc <= -11056) {
        return 'Y';
    }

    if ($asc >= -11055 && $asc <= -10247) {
        return 'Z';
    }
    return null;
}

/**
 * 按字母排序
 * @param  array $data
 * @return array
 */
function sortInitials(array $data)
{
    $sortData = [];
    foreach ($data as $key => $value) {
        $sortData[$value['initials']][] = $value;
    }
    ksort($sortData);
    return $sortData;
}

/**
 * 二维数组根据分组排序
 * @param  array $data 二维数组
 * @param  string $targetKey 分组条件的键名
 * @return array             根据分组条件关联的二维数组
 */
function groupByParam($data = [], $targetKey)
{
    $grouped = [];
    foreach ($data as $value) {
        $grouped[$value[$targetKey]][] = $value;
    }
    if (func_num_args() > 2) {
        $args = func_get_args();
        foreach ($grouped as $key => $value) {
            $param = array_merge([$value], array_slice($args, 2, func_num_args()));
            $grouped[$key] = call_user_func_array('array_group_by', $param);
        }
    }
    return $grouped;
}

/**
 * 二维数组根据首字母分组排序
 * @param  array $data 二维数组
 * @param  string $targetKey 首字母的键名
 * @return array             根据首字母关联的二维数组
 */
function groupByInitials(array $data, $targetKey = 'brand')
{
    $data = array_map(function ($item) use ($targetKey) {
        return array_merge($item, [
            'initials' => getInitials($item[$targetKey]),
        ]);
    }, $data);
    $data = sortInitials($data);
    return $data;
}

/**
 * 验证身份证
 * @param $idCard string 身份证号
 * @return bool
 */
function checkIdCard($idCard)
{
    if (empty($idCard)) {
        return false;
    }
    $City = array(11 => "北京", 12 => "天津", 13 => "河北", 14 => "山西", 15 => "内蒙古", 21 => "辽宁", 22 => "吉林", 23 => "黑龙江", 31 => "上海", 32 => "江苏", 33 => "浙江", 34 => "安徽", 35 => "福建", 36 => "江西", 37 => "山东", 41 => "河南", 42 => "湖北", 43 => "湖南", 44 => "广东", 45 => "广西", 46 => "海南", 50 => "重庆", 51 => "四川", 52 => "贵州", 53 => "云南", 54 => "西藏", 61 => "陕西", 62 => "甘肃", 63 => "青海", 64 => "宁夏", 65 => "新疆", 71 => "台湾", 81 => "香港", 82 => "澳门", 91 => "国外");
    $iSum = 0;
    $idCardLength = strlen($idCard);
    //长度验证
    if (!preg_match('/^\d{17}(\d|x)$/i', $idCard) and !preg_match('/^\d{15}$/i', $idCard)) {
        return false;
    }
    //地区验证
    if (!array_key_exists(intval(substr($idCard, 0, 2)), $City)) {
        return false;
    }
    // 15位身份证验证生日，转换为18位
    if ($idCardLength == 15) {
        $sBirthday = '19' . substr($idCard, 6, 2) . '-' . substr($idCard, 8, 2) . '-' . substr($idCard, 10, 2);
        //匹配日期格式
        if (!checkDateFormat($sBirthday)) {
            return false;
        }
        $d = new DateTime($sBirthday);
        $dd = $d->format('Y-m-d');
        if ($sBirthday != $dd) {
            return false;
        }
        $idCard = substr($idCard, 0, 6) . "19" . substr($idCard, 6, 9);//15to18
        $Bit18 = getVerifyBit($idCard);//算出第18位校验码
        $idCard = $idCard . $Bit18;
    }
    // 判断是否大于2078年，小于1900年
    $year = substr($idCard, 6, 4);
    if ($year < 1900 || $year > 2078) {
        return false;
    }
    //18位身份证处理
    $sBirthday = substr($idCard, 6, 4) . '-' . substr($idCard, 10, 2) . '-' . substr($idCard, 12, 2);
    //匹配日期格式
    if (!checkDateFormat($sBirthday)) {
        return false;
    }
    $d = new DateTime($sBirthday);
    $dd = $d->format('Y-m-d');
    if ($sBirthday != $dd) {
        return false;
    }
    //身份证编码规范验证
    $idCard_base = substr($idCard, 0, 17);
    if (strtoupper(substr($idCard, 17, 1)) != getVerifyBit($idCard_base)) {
        return false;
    }
    return true;
}

/**
 * 计算身份证校验码，根据国家标准GB 11643-1999
 * @param $idCard_base string 身份证号
 * @return bool|mixed
 * */
function getVerifyBit($idCard_base)
{
    if (strlen($idCard_base) != 17) {
        return false;
    }
    //加权因子
    $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
    //校验码对应值
    $verify_number_list = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
    $checksum = 0;
    for ($i = 0; $i < strlen($idCard_base); $i++) {
        $checksum += substr($idCard_base, $i, 1) * $factor[$i];
    }
    $mod = $checksum % 11;
    $verify_number = $verify_number_list[$mod];
    return $verify_number;
}

/**
 * 功能：计算两个日期相隔多少年，多少月，多少天
 * @param string $date1 [格式如：2011-11-5]
 * @param string $date2 [格式如：2012-12-01]
 * @return array array('年','月','日');
 */
function diffDate($date1, $date2)
{
    if (strtotime($date1) > strtotime($date2)) {
        $tmp = $date2;
        $date2 = $date1;
        $date1 = $tmp;
    }
    list($Y1, $m1, $d1) = explode('-', $date1);
    list($Y2, $m2, $d2) = explode('-', $date2);
    $Y = $Y2 - $Y1;
    $m = $m2 - $m1;
    $d = $d2 - $d1;
    if ($d < 0) {
        $d += (int)date('t', strtotime("-1 month $date2"));
        $m--;
    }
    if ($m < 0) {
        $m += 12;
        $Y--;
    }
    return array('year' => $Y, 'month' => $m, 'day' => $d);
}

/**
 * 生成编号
 * @param string $prefix
 * @return string
 */
function makeNum($prefix = '')
{
    return $prefix . date('Ymd') . str_pad(mt_rand(10000000, 99999999), 5, '0', STR_PAD_LEFT);
//    return $prefix . date('Y', time()) . base_convert(uniqid(), 16, 10) . mt_rand(10, 99);
}

/**
 * 生成编号
 * @return string
 */
function makeCode()
{
    return date('Ymd') . str_pad(mt_rand(10000000, 99999999), 5, '0', STR_PAD_LEFT);
}


/**
 * 去除数组中重复数据
 * @param $array
 * @return array
 */
function a_array_unique($array)//写的比较好（写方法）
{
    $out = []; //定义变量out为一个数组
    foreach ($array as $key => $value) //将$array数组按照$key=>$value的样式进行遍历
    {
        if (!in_array($value, $out))//如果$value不存在于out数组中，则执行
        {
            $out[$key] = $value; //将该value值存入out数组中
        }
    }
    return $out; //最后返回数组out
}

/**
 * 功能：隐藏转换*号
 * @param string $string
 * @param int $sublen
 * @param int $start
 * @param string $code
 * @return string
 */
function cut_str($string, $sublen, $start = 0, $code = 'UTF-8')
{
    if ($code == 'UTF-8') {
        $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
        preg_match_all($pa, $string, $t_string);
        if (count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen));
        return join('', array_slice($t_string[0], $start, $sublen));
    } else {
        $start = $start * 2;
        $sublen = $sublen * 2;
        $strlen = strlen($string);
        $tmpstr = '';
        for ($i = 0; $i < $strlen; $i++) {
            if ($i >= $start && $i < ($start + $sublen)) {
                if (ord(substr($string, $i, 1)) > 129) {
                    $tmpstr .= substr($string, $i, 2);
                } else {
                    $tmpstr .= substr($string, $i, 1);
                }
            }
            if (ord(substr($string, $i, 1)) > 129) $i++;
        }
        return $tmpstr;
    }
}

/**
 * 功能：隐藏转换*号
 * @param string $str
 * @param int $type 类型：1-手机；2-身份证；3-IP
 * @return mixed
 */
function searchAndReplace($str, $type = 1)
{
    if ($type == 1) {
        return preg_replace('/(^.*)\d{4}(\d{4})$/', '\\1****\\2', $str);
    } else if ($type == 2) {
        return strlen($str) == 15 ? substr_replace($str, "****", 8, 4) : (strlen($str) == 18 ? substr_replace($str, "****", 10, 4) : $str);
    } else if ($type == 3) {
        return preg_replace('/((?:\d+\.){3})\d+/', "\\1*", $str);
    }
}

/**
 * 正则检查电话号码是否正确
 * @param $tel string 电话号码
 * @param $type string 电话类型 sj=>手机 Tel=>座机 400=> 400电话
 * @return boolean
 */
function check_tel($tel, $type = '')
{
    $regx_arr = array(
        'mobile' => '/^(\+?86-?)?(13|14|15|16|17|18|19)[0-9]{9}$/',
        'tel' => '/^(010|02\d{1}|0[3-9]\d{2})-\d{7,9}(-\d+)?$/',
        '400' => '/^400(-\d{3,4}){2}$/',
    );
    if ($type && isset($regx_arr[$type])) {
        return preg_match($regx_arr[$type], $tel) ? true : false;
    }
    foreach ($regx_arr as $regx) {
        if (preg_match($regx, $tel)) {
            return true;
        }
    }
    return false;
}

/**
 * 验证邮箱格式
 * @param $email
 * @return bool
 */
function check_email($email)
{
    if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email)) {
        return false;
    }
    return true;
}

/**
 * 验证邮编
 * @param $code
 * @return bool
 */
function check_code($code)
{
    if (!preg_match('/^[1-9]\d{5}(?!\d)$/', $code)) {
        return false;
    }
    return true;
}

/**
 * 功能：验证时间格式
 * @param string $date 时间
 * @return bool
 */
function checkDateFormat($date)
{
    if (preg_match("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts)) {
        //检测是否为日期
        if (checkdate($parts[2], $parts[3], $parts[1]))
            return true;
        else
            return false;
    } else
        return false;
}

/**
 * 返回可读性更好的文件尺寸
 */
function human_file_size($bytes, $decimals = 2)
{
    $size = ['B', 'kB', 'MB', 'GB', 'TB', 'PB'];
    $factor = floor((strlen($bytes) - 1) / 3);
    return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$size[$factor];
}

/**
 * 判断文件的MIME类型是否为图片
 */
function is_image($mimeType)
{
    return starts_with($mimeType, 'image/');
}

/**
 * 模拟post进行url请求
 * @param  $url string
 * @param  $params string
 * @return mixed
 */
function request_post($url = '', $params = '')
{
    if (empty($url) || empty($params)) {
        return false;
    }
    $postUrl = $url;
    $curlPost = $params;
    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL, $postUrl);//抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($ch);//运行curl
    curl_close($ch);
    return $data;
}

function request_get($url = '')
{
    if (empty($url)) {
        return false;
    }
    //初始化
    $curl = curl_init();
    //设置抓取的url
    curl_setopt($curl, CURLOPT_URL, $url);
    //设置头文件的信息作为数据流输出
    curl_setopt($curl, CURLOPT_HEADER, 0);
    //设置获取的信息以文件流的形式返回，而不是直接输出。
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:'));
    //执行命令
    $data = curl_exec($curl);
    //关闭URL请求
    curl_close($curl);
    //显示获得的数据
    return $data;
}

/**
 * 微信展示时间的方法
 * @param $addTime
 * @return string
 */
function getChatTimeStr($addTime)
{
    $nowTime = time();
    if ($addTime > $nowTime) {
        return "";
    }
    //返回的时间
    $timeStr = "";
    //获取当前时间
    $addTime = explode(',', date('Y,n,j,w,a,h,i,y', $addTime));//年，月，日，星期，上下午，时，分
    $nowTime = explode(',', date('Y,n,j,w,a,h,i,y', $nowTime));
    $dayPerMonthAddTime = getDayPerMonth($addTime[0]);
    $week = array(0 => "星期日", 1 => "星期一", 2 => "星期二", 3 => "星期三", 4 => "星期四", 5 => "星期五", 6 => "星期六");
    //如果时间差小于一天的,显示（上午 时间） / （下午 时间）
    if ($addTime[0] == $nowTime[0] && $addTime[1] == $nowTime[1] && $addTime[2] == $nowTime[2]) {
        $timeStr .= getAmOrPm($addTime['4']) . " " . $addTime[5] . ":" . $addTime[6];
    } else if (($addTime[0] == $nowTime[0] && $addTime[1] == $nowTime[1] && $addTime[2] == $nowTime[2] - 1)
        || ($addTime[0] == $nowTime[0] && $nowTime[1] - $addTime[1] == 1 && $dayPerMonthAddTime[$addTime[1]] == $addTime[2] && $nowTime[2] == 1)
        || ($nowTime[0] - $addTime[0] == 1 && $addTime[1] == 12 && $addTime[2] == 31 && $nowTime[1] == 1 && $nowTime[2] == 1)) { //如果时间差在昨天,三种情况（同一月份内跨一天、月末跨越到月初、年末跨越到年初）显示格式：昨天 时:分 上午/下午
        $timeStr .= "昨天 " . getAmOrPm($addTime['4']) . " " . $addTime[5] . ":" . $addTime[6] . " ";
    } else if (($addTime[0] == $nowTime[0] && $addTime[1] == $nowTime[1] && $nowTime[2] - $addTime[2] < 7)
        || ($addTime[0] == $nowTime[0] && $nowTime[1] - $addTime[1] == 1 && $dayPerMonthAddTime[$addTime[1]] - $addTime[2] + $nowTime[2] < 7
            || ($nowTime[0] - $addTime[0] == 1 && $addTime[1] == 12 && $nowTime[1] == 1 && 31 - $addTime[2] + $nowTime[2] < 7))) { //如果时间差在一个星期之内的,也是三种情况，显示格式：星期 时:分 上午/下午

        $timeStr .= $week[$addTime[3]] . " " . getAmOrPm($addTime['4']) . " " . $addTime[5] . ":" . $addTime[6];
    } else { //显示格式：年-月-日 上午/下午 时:分
//        $timeStr .= $addTime[1] . "/" . $addTime[2] . "/" . $addTime[7] . " " . $addTime[5] . ":" . $addTime[6];
        $timeStr .= $addTime[0] . "-" . $addTime[1] . "-" . $addTime[2] . " " . getAmOrPm($addTime['4']) . " " . $addTime[5] . ":" . $addTime[6];
    }
//    if ($addTime[4] == "am") {
//        $timeStr .= " 上午";
//    } else if ($addTime[4] == "pm") {
//        $timeStr .= " 下午";
//    }
    return $timeStr;
}

/**
 * 获取上午还是下午
 * @param $addTime
 * @return string
 */
function getAmOrPm($addTime)
{
    if ($addTime == "am") {
        return '上午';
    } else if ($addTime == "pm") {
        return '下午';
    }
}

/**
 * 根据年份获取每个月份的总天数和每年最后一个月的天数
 * @param $year
 * @return array
 */
function getDayPerMonth($year)
{
    $arr = array(
        1 => 31,
        3 => 31,
        4 => 30,
        5 => 31,
        6 => 30,
        7 => 31,
        8 => 31,
        9 => 30,
        10 => 31,
        11 => 30,
        12 => 31
    );
    //闰年
    if (($year % 4 == 0 && $year % 100 != 0) || ($year % 400 == 0)) {
        $arr[2] = 29;
    } else {
        $arr[2] = 28;
    }
    return $arr;
}

/**
 * 根据IP获取城市
 * @param string $ip
 * @return bool|mixed
 */
function getIpLookup($ip = '')
{
    if ($ip == '') {
        $url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json";
        $ip = json_decode(file_get_contents($url), true);
        $data = $ip;
    } else {
        $url = "http://ip.taobao.com/service/getIpInfo.php?ip=" . $ip;
        $ip = json_decode(file_get_contents($url));
        if ((string)$ip->code == '1') {
            return false;
        }
        $data = (array)$ip->data;
    }
    return $data;
}

/**
 * 遍历获取目录下的指定类型的文件
 * @param $path
 * @param $allowFiles
 * @param array $files
 * @return array|null
 */
function getFiles($path, $allowFiles, &$files = array())
{
    if (!is_dir($path)) return null;
    if (substr($path, strlen($path) - 1) != '/') $path .= '/';
    $handle = opendir($path);
    while (false !== ($file = readdir($handle))) {
        if ($file != '.' && $file != '..') {
            $path2 = $path . $file;
            if (is_dir($path2)) {
                getfiles($path2, $allowFiles, $files);
            } else {
                if (preg_match("/\.(" . $allowFiles . ")$/i", $file)) {
                    $files[] = array(
                        'url' => substr($path2, strlen($_SERVER['DOCUMENT_ROOT'])),
                        'mtime' => filemtime($path2)
                    );
                }
            }
        }
    }
    return $files;
}

/**
 * 日期转换
 * @param $time
 * @return false|string
 */
function time_turn($time)
{
    if (strtotime($time)) {
        return date('Y/m/d H:i:s', strtotime($time));
    } else {
        return '';
    }
}

/**
 *考勤机数据
 */
function attendPush($data, $api)
{
    $requesttime = time();
    $account = '1a896936562d964896c804caf34c746b';
    $str = 'http://yun.kqapi.com' . $api . '?';
    $push_sign = 'somorn2019';
    $data['requesttime'] = $requesttime;
    $data['account'] = $account;
    ksort($data);
    $sign = md5(implode('', $data) . $push_sign);
    $data['sign'] = $sign;
    $url = '';
    foreach ($data as $k => $v) {
        $url .= $k . '=' . $v . '&';
    }
    $url = mb_substr($url, 0, mb_strlen($url, 'utf-8') - 1, 'utf-8');
    $str .= $url;
    $json = request_get($str);
    return json_decode($json, true);
}

/**
 * 返回指定日期是否为工作日
 * @param $date 0000-00-00
 * @return mixed
 */
function sign_date($date)
{
    $str = 'http://api.goseek.cn/Tools/holiday?date=' . $date;
    $date = request_get($str);
    $date = json_decode($date, true);
    return $date['data'];
}


//模板消息推送
function _msgPush($openid, $content, $title, $keyword2, $type = 1, $id = 0)
{
    $app = \EasyWeChat\Factory::officialAccount(config('wechat.easy_wechat'));

    $data = [];
    $url = config('app.url');
    switch ($type) {
        case 1://会议通知
            $data = [
                'touser' => $openid,
                'template_id' => 'wz7Sf6BdpY3zPrhEHSF5gAu2t19CS9gxW573FoTTTcA',
                'url' => $url . 'wechat/#/meetDetail?id=' . $id,
                'data' => [
                    'first' => ['value' => $content],
                    'keyword1' => ['value' => $title, "color" => "#FF0000"],
                    'keyword2' => ['value' => $keyword2, "color" => "#FF0000"],
                    'remark' => ['value' => '']
                ]
            ];
            break;
        case 2://抽查
            $data = [
                'touser' => $openid,
                'template_id' => 'bCDYlYc7-Y05RmAuIeT1MDwV6Upj3bATyTmxtdyEnVE',
                'url' => $url . 'wechat/#/memoCount?id=' . $id,
                'data' => [
                    'first' => ['value' => $content],
                    'keyword1' => ['value' => $title, "color" => "#FF0000"],
                    'keyword2' => ['value' => $keyword2, "color" => "#FF0000"],
                    'remark' => ['value' => '']
                ]
            ];
            break;
        case 3://审核
            $data = [
                'touser' => $openid,
                'template_id' => 'mo2R5yD4jYaWp81imeP6PwLcpCjadTtcd1z2tSp6YLk',
                'url' => $url . 'wechat/',
                'data' => [
                    'first' => ['value' => $content],
                    'keyword1' => ['value' => $title, "color" => "#FF0000"],
                    'keyword2' => ['value' => $keyword2, "color" => "#FF0000"],
                    'remark' => ['value' => '']
                ]
            ];
            break;
        case 4://抽查结果
            $data = [
                'touser' => $openid,
                'template_id' => 'bCDYlYc7-Y05RmAuIeT1MDwV6Upj3bATyTmxtdyEnVE',
                'url' => $url . 'wechat/#/memoCount?id=' . $id,
                'data' => [
                    'first' => ['value' => $content],
                    'keyword1' => ['value' => $title, "color" => "#FF0000"],
                    'keyword2' => ['value' => $keyword2, "color" => "#FF0000"],
                    'remark' => ['value' => '']
                ]
            ];
            break;
        case 5:
            $data = [
                'touser' => $openid,
                'template_id' => 'lalB477utO2MZ6i7INaMhnZ_YXx2M7yCUtN7cs3Px3E',
                'url' => $url . 'wechat/#/memoCount?id=' . $id,
                'data' => [
                    'first' => ['value' => $content],
                    'keyword2' => ['value' => $title, "color" => "#FF0000"],
                    'keyword3' => ['value' => $keyword2, "color" => "#FF0000"],
                    'remark' => ['value' => '']
                ]
            ];
            break;
        case 6:
            $data = [
                'touser' => $openid,
                'template_id' => 'QGLiAOZjo6EgJ7Gm5iHC7M_bfDS4AiBi-CRoe8RtUKg',
                'url' => $url . 'wechat/#/serverInfo?id=' . $id,
                'data' => [
                    'first' => ['value' => $content],
                    'keyword1' => ['value' => $title, "color" => "#FF0000"],
                    'keyword2' => ['value' => $keyword2, "color" => "#FF0000"],
                    'remark' => ['value' => '']
                ]
            ];
            break;
    }

    if (!$data) {
        return false;
    }
    $send = $app->template_message->send($data);

    return $send;

    \Log::info($send);

    return true;


}

/**
 * 同步公众号菜单
 * @return mixed
 */
function addMenu()
{
    $list = \App\Models\PublicColumn::getColumn();
    if ($list) {
//        $url = config('app.url');
        foreach ($list as &$item) {
            if (isset($item['sub_button'])) {
                foreach ($item['sub_button'] as &$value) {
                    $value['type'] = 'view';
                }
                unset($value['id']);
            }
//            if ($item['id'] == 3) {
//                $item['type'] = 'view';
//                $item['url'] = $url . "wechat/";
//            }
            unset($item['id']);
        }
    }
//    $data = \App\Models\ArticleColumn::where(['is_disable' => 0, 'status' => 0])->orderBy('sort')->get(['id', 'title'])->toArray();
//    $dang = [
//        "name" => "党建任务",
//        "sub_button" => [
//            [
//                "type" => "view",
//                "name" => "先锋话题",
//                "url" => "http://www.cqukon.com/wechat/#/firstTopic"
//            ],
//            [
//                "type" => "view",
//                "name" => "每周党课",
//                "url" => "http://www.cqukon.com/wechat/#/partyCourse"
//            ],
//            [
//                "type" => "view",
//                "name" => "有奖答题",
//                "url" => "http://www.cqukon.com/wechat/#/answerStart"
//            ],
//            [
//                "type" => "view",
//                "name" => "经典推送",
//                "url" => "http://www.cqukon.com/wechat/#/pushList"
//            ],
//            [
//                "type" => "view",
//                "name" => "文件下载",
//                "url" => "http://www.cqukon.com/wechat/#/downFile"
//            ],
//        ],
//    ];
//    $info = [
//        "type" => "view",
//        "name" => "个人中心",
//        "url" => "http://www.cqukon.com/wechat/"
//    ];
//    $inter = [
//        "name" => "企业文化",
//        "sub_button" => [
//
//        ],
//    ];
//    foreach ($data as $datum) {
//        $inter['sub_button'][] = [
//            "type" => "view",
//            "name" => $datum['title'],
//            "url" => "http://www.cqukon.com/wechat/#/workNews?type=" . $datum['id']
//        ];
//    }
//    $buttons = [
//        $inter, $dang, $info
//    ];
//    dd($buttons);
    $app = EasyWeChat\Factory::officialAccount(config('wechat.easy_wechat'));
    $code = $app->menu->create($list);
//    $code = json_decode($code, true);
    if ($code['errcode'] != 0) {
        return false;
    }
    return true;
}

function imgPath($img_path)
{
    if (is_array($img_path)) {
        $path = [];
        foreach ($img_path as $val) {
            if (!array_key_exists('scheme', parse_url($val)) && !empty($val)) {
                $res = \App\Models\Config::where('key', 'domain_name')->value('value') . $val;
                $path[] = $res;
            } else {
                $path[] = $val;
            }
        }
        return $path;
    } else {
        if (!array_key_exists('scheme', parse_url($img_path)) && !empty($img_path)) {
            $img_path = \App\Models\Config::where('key', 'domain_name')->value('value') . $img_path;
        }
        return $img_path ?: '';
    }
}

/**
 * 随机获取颜色
 * @return string
 */
function randColor()
{
    $colors = array();
    for ($i = 0; $i < 6; $i++) {
        $colors[] = dechex(rand(0, 15));
    }
    return implode('', $colors);
}

//BD-09(百度)坐标转换成GCJ-02(火星，高德)坐标
//@param bd_lon 百度经度
//@param bd_lat 百度纬度

function bd_decrypt($bd_lon, $bd_lat)
{
    $x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    $x = $bd_lon - 0.0065;
    $y = $bd_lat - 0.006;
    $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi);
    $theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi);
    // $data['gg_lon'] = $z * cos($theta);
    // $data['gg_lat'] = $z * sin($theta);
    $gg_lon = $z * cos($theta);
    $gg_lat = $z * sin($theta);
    // 保留小数点后六位
    $data['lng'] = round($gg_lon, 8);
    $data['lat'] = round($gg_lat, 8);
    return $data;
}

//GCJ-02(火星，高德)坐标转换成BD-09(百度)坐标
//@param bd_lon 百度经度
//@param bd_lat 百度纬度
function bd_encrypt($gg_lon, $gg_lat)
{
    $x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    $x = $gg_lon;
    $y = $gg_lat;
    $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi);
    $theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi);
    $bd_lon = $z * cos($theta) + 0.0065;
    $bd_lat = $z * sin($theta) + 0.006;
    // 保留小数点后六位
    $data['lng'] = round($bd_lon, 8);
    $data['lat'] = round($bd_lat, 8);
    return $data;
}